package drawingBoard.action;

import drawingBoard.ImageFrame;
import drawingBoard.state.EndState;
import drawingBoard.state.MiddleState;
import drawingBoard.state.StartState;
import drawingBoard.memento.CareTaker;
import drawingBoard.myFile.MyImageFile;

import javax.swing.*;

/*import drawing.ImageFrame;
import drawing.State.*;
import drawing.memento.CareTaker;
import drawing.myFile.MyImageFile;*/

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;

public class KeyboardListener extends JPanel implements KeyListener {

	private static final long serialVersionUID = 1L;
	public BufferedImage myImage;

	@Override
	public void keyTyped(KeyEvent e) {
	}

	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode() == 90 && e.isControlDown()) {  //keycode=90： z或Z；整个条件是按Ctrl+z或Ctrl+Z
			System.out.println("");
			Undo(); // 撤销
		} else if (e.getKeyCode() == 89 && e.isControlDown()) {  //Ctrl+y或Ctrl+Y
			Redo(); // 恢复
		} else if (e.getKeyCode() == 83 && e.isControlDown()) {   //Ctrl+s或Ctrl+S
			Save(); // 保存
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
	}

	private void Undo() { // 撤销
		ImageFrame.getInstance().originator.getStateFromMemento(ImageFrame.getInstance().careTaker.Undo());
		myImage = ImageFrame.getInstance().originator.getState();
		ImageFrame.getInstance().my_draw(myImage);
		if (CareTaker.getInstance().index != 0) {
			MiddleState middleState = new MiddleState();
			middleState.doAction(ImageFrame.getInstance().context);
		} else {
			StartState startState = new StartState();
			startState.doAction(ImageFrame.getInstance().context);
		}
	}

	private void Redo() {  // 恢复
		ImageFrame.getInstance().originator.getStateFromMemento(ImageFrame.getInstance().careTaker.Redo());
		myImage = ImageFrame.getInstance().originator.getState();
		ImageFrame.getInstance().my_draw(myImage);
		if (CareTaker.getInstance().index != CareTaker.getInstance().size() - 1) {
			MiddleState middleState = new MiddleState();
			middleState.doAction(ImageFrame.getInstance().context);
		} else {
			EndState endState = new EndState();
			endState.doAction(ImageFrame.getInstance().context);
		}
	}

	private void Save() {  // 保存
		MyImageFile myImageFile = new MyImageFile();
		myImageFile.save(true, ImageFrame.getInstance());
	}
}
